package com.kevin.v2.spring.formework.aop.aspect;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 通知方法执行类
 */
public abstract class KvAbstractAspectAdvice {
   //通知方法
   private Method aspectMethod;
   //通知类
   private Object aspectTarget;

   public KvAbstractAspectAdvice (Method aspectMethod, Object aspectTarget) {
      this.aspectMethod = aspectMethod;
      this.aspectTarget = aspectTarget;
   }

   /**
    * 执行通知的方法
    * @param joinPoint
    * @param returnValue
    * @param throwable
    * @return
    */
   protected Object invokeAdviceMethod (KvJoinPoint joinPoint, Object returnValue, Throwable throwable)  {
      Class<?>[] paramTpyes = this.aspectMethod.getParameterTypes();
      if (paramTpyes == null || paramTpyes.length == 0) {
         try {
            return this.aspectMethod.invoke(aspectTarget);
         } catch (IllegalAccessException e) {
            e.printStackTrace();
         } catch (InvocationTargetException e) {
            e.printStackTrace();
         }
      }else {
         Object[] args = new Object[paramTpyes.length];
         for (int i = 0; i < paramTpyes.length; i++) {
            if (paramTpyes[i] == KvJoinPoint.class) {
               args[i] = joinPoint;
            } else if (paramTpyes[i] == Throwable.class) {
               args[i] = throwable;
            }else if (paramTpyes[i] == Object.class) {
               args[i] = returnValue;
            }
         }
         try {
            return this.aspectMethod.invoke(aspectTarget, args);
         } catch (IllegalAccessException e) {
            e.printStackTrace();
         } catch (InvocationTargetException e) {
            e.printStackTrace();
         }
      }
      return null;
   }
}
